<script setup>
import { ref, computed, onMounted, onUnmounted  } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import EmptyContent from "../components/EmptyContent.vue";
import SvgIcon from "@/components/SvgIcon/index.vue";

import { useUserStore } from "@/store/modules/user";
import {
  getFollowsListApi,
  followUserApi,
  unfollowUserApi,
  getFansListApi,
} from "@/api/follow";

const userStore = useUserStore();

// 分页参数
const pageParams = ref({
  currentPage: 1,
  pageSize: 10,
  hasMore: true,
  loading: false,
  initialized: false,
});

// 关注列表数据
const concernList = ref([]);

// 关注列表元素引用，用于滚动加载
const concernListRef = ref(null);

// 是否有关注
const hasConcerns = computed(() => {
  return pageParams.value.initialized && concernList.value.length > 0;
});

// 是否为初始加载状态
const isInitialLoading = computed(() => {
  return !pageParams.value.initialized && pageParams.value.loading;
});

// 模拟API调用获取关注列表
async function fetchConcernList(page = 1, append = false) {
  if ((!pageParams.value.hasMore && page > 1) || pageParams.value.loading)
    return;

  pageParams.value.loading = true;

  try {
    // 调用真实 API 获取关注列表
    const params = {
      page: page,
      limit: pageParams.value.pageSize,
    };
    const response = await getFollowsListApi(userStore.userInfo.id, params);


    // 处理用户数据，添加isFollowing标记
    const users = (response.items || []).map((user) => ({
      ...user,
      isFollowing: true, // 默认所有获取到的用户都是已关注的
    }));

    if (append) {
      // 追加数据
      concernList.value = [...concernList.value, ...users];
    } else {
      // 替换数据
      concernList.value = users;
    }

    // 更新分页信息
    pageParams.value.currentPage = response.page || page;
    pageParams.value.hasMore = (response.page < response.totalPages);
    pageParams.value.initialized = true;
  } catch (error) {
    console.error("获取关注列表失败:", error);
    ElMessage.error("获取关注列表失败，请稍后重试");
  } finally {
    pageParams.value.loading = false;
  }
}

// 监听滚动事件，实现无限加载
function setupScrollListener() {
  if (!concernListRef.value) return;

  const listElement = concernListRef.value;
  listElement.addEventListener("scroll", handleScroll);

  return () => {
    listElement.removeEventListener("scroll", handleScroll);
  };
}

// 处理滚动事件（节流版本）
let scrollTimeout = null;
function handleScroll(e) {
  if (scrollTimeout) return;

  scrollTimeout = setTimeout(() => {
    const element = e.target;
    if (element.scrollHeight - element.scrollTop - element.clientHeight < 100) {
      if (pageParams.value.hasMore && !pageParams.value.loading) {
        loadMore();
      }
    }
    scrollTimeout = null;
  }, 200);
}

// 加载更多数据
function loadMore() {
  const nextPage = pageParams.value.currentPage + 1;
  fetchConcernList(nextPage, true);
}

// 添加关注用户函数
async function followUser(user) {
  try {
    // 调用关注API
    await followUserApi(userStore.userInfo.id, user.id);

    // 更新用户状态
    user.isFollowing = true;

     // 更新store中的用户数据
     if (userStore.userInfo) {
      const currentFollowingCount = userStore.userInfo.following_count || 0;
      userStore.setUserInfo({
        ...userStore.userInfo,
        following_count: currentFollowingCount + 1
      });
    }

    ElMessage({
      type: "success",
      message: `已关注 ${user.username}`,
    });
  } catch (error) {
    console.error("关注用户失败:", error);
    ElMessage.error("关注用户失败，请稍后重试");
  }
}

// 修改取消关注函数，不要从列表中删除用户，而是更新其状态
async function unfollow(user) {
  ElMessageBox.confirm(`确定要取消关注 ${user.username} 吗？`, "取消关注", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        // 调用取消关注 API
        await unfollowUserApi(userStore.userInfo.id, user.id);

        // 更新用户状态而不是移除
        user.isFollowing = false;

        // 更新store中的用户数据
        if (userStore.userInfo) {
          const currentFollowingCount = userStore.userInfo.following_count || 0;
          // 确保不会出现负数
          const newCount = Math.max(0, currentFollowingCount - 1);
          userStore.setUserInfo({
            ...userStore.userInfo,
            following_count: newCount
          });
        }

        ElMessage({
          type: "success",
          message: `已取消关注 ${user.username}`,
        });
      } catch (error) {
        console.error("取消关注失败:", error);
        ElMessage.error("取消关注失败，请稍后重试");
      }
    })
    .catch(() => {
      // 用户取消，不执行操作
    });
}

// 格式化粉丝数量
function formatFansCount(count) {
  if (count >= 10000) {
    return (count / 10000).toFixed(1) + "万";
  }
  return count.toString();
}

// 组件挂载时加载初始数据
onMounted(() => {
  fetchConcernList();

  // 设置滚动监听
  const cleanup = setupScrollListener();
  if (cleanup) {
    // 组件卸载时清除监听器
    onUnmounted(cleanup);
  }
});
</script>

<template>
  <div class="content-panel">
    <h3>我的关注</h3>

    <!-- 加载中状态 -->
    <div v-if="isInitialLoading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 有关注用户时显示列表 -->
    <div v-show="hasConcerns" ref="concernListRef" class="concern-list">
      <div v-for="user in concernList" :key="user.id" class="user-card">
        <div class="user-avatar">
          <img :src="user.avatar" :alt="user.username" />
          <span v-if="user.isOfficial" class="official-badge">官方</span>
        </div>

        <div class="user-info">
          <div class="user-name-row">
            <h4 class="user-name">{{ user.username }}</h4>
            <span class="user-type">{{ user.type }}</span>
            <span v-if="user.isMutual" class="mutual-badge">互相关注</span>
          </div>

          <p class="user-description">{{ user.description }}</p>

          <div class="user-stats">
            <span class="fans-count"
              >{{ formatFansCount(user.fansCount) }}粉丝</span
            >
          </div>
        </div>

        <div class="user-actions">
          <div class="user-actions">
            <button
              v-if="user.isFollowing"
              class="unfollow-btn"
              @click.stop="unfollow(user)"
            >
              取消关注
            </button>
            <button v-else class="follow-btn" @click.stop="followUser(user)">
              关注
            </button>
          </div>
        </div>
      </div>

      <!-- 底部加载提示 -->
      <div v-if="pageParams.loading" class="loading-more">
        <div class="loading-spinner small"></div>
        <span>加载更多...</span>
      </div>
      <div
        v-else-if="!pageParams.hasMore && concernList.length > 0"
        class="no-more"
      >
        没有更多关注了
      </div>
    </div>

    <!-- 无关注用户时显示空状态 -->
    <EmptyContent
      v-if="!hasConcerns && pageParams.initialized"
      icon="🔍"
      text="暂无关注用户"
      buttonText="发现用户"
      @action="() => {}"
    />
  </div>
</template>

<style scoped lang="scss">
.content-panel {
  display: flex;
  flex-direction: column;
  height: 100%;

  h3 {
    margin-top: 8px;
    margin-bottom: 16px;
    font-weight: 500;
    font-size: 1.4rem;
    color: #ffffff;
    border-left: 4px solid #0096ff;
    padding-left: 12px;
  }

  .loading-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #99a3a7;
  }

  .loading-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid rgba(0, 150, 255, 0.3);
    border-radius: 50%;
    border-top-color: #0096ff;
    animation: spin 1s ease-in-out infinite;
    margin-bottom: 12px;

    &.small {
      width: 24px;
      height: 24px;
      border-width: 2px;
      margin-bottom: 0;
      margin-right: 10px;
    }
  }

  .concern-list {
    flex: 1;
    overflow-y: auto;
    padding: 0 16px 16px;

    .user-card {
      display: flex;
      padding: 16px;
      background-color: #1f2129;
      border-radius: 10px;
      margin-bottom: 12px;
      transition: all 0.2s ease;

      &:hover {
        background-color: #272933;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
      }

      .user-avatar {
        position: relative;
        width: 60px;
        height: 60px;
        flex-shrink: 0;
        margin-right: 16px;

        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
          object-fit: cover;
          border: 2px solid #3a3d4a;
        }

        .official-badge {
          position: absolute;
          bottom: -2px;
          right: -2px;
          background-color: #ff9500;
          color: #fff;
          font-size: 0.65rem;
          padding: 1px 4px;
          border-radius: 4px;
          font-weight: bold;
        }
      }

      .user-info {
        flex: 1;
        overflow: hidden;

        .user-name-row {
          display: flex;
          align-items: center;
          margin-bottom: 6px;

          .user-name {
            margin: 0;
            font-size: 1.1rem;
            color: #ffffff;
            font-weight: 500;
          }

          .user-type {
            margin-left: 8px;
            font-size: 0.75rem;
            color: #99a3a7;
            background-color: rgba(153, 163, 167, 0.1);
            padding: 1px 6px;
            border-radius: 4px;
          }

          .mutual-badge {
            margin-left: 8px;
            font-size: 0.75rem;
            color: #0096ff;
            background-color: rgba(0, 150, 255, 0.1);
            padding: 1px 6px;
            border-radius: 4px;
          }
        }

        .user-description {
          margin: 0;
          font-size: 0.9rem;
          color: #99a3a7;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          margin-bottom: 8px;
        }

        .user-stats {
          font-size: 0.85rem;
          color: #6c7a83;

          .fans-count {
            display: inline-block;
          }
        }
      }

      .user-actions {
        display: flex;
        align-items: center;

        .unfollow-btn,
        .follow-btn {
          height: 32px;
          background-color: transparent;
          border-radius: 4px;
          padding: 0 12px;
          font-size: 0.9rem;
          cursor: pointer;
          transition: all 0.2s ease;
        }

        .unfollow-btn {
          border: 1px solid #99a3a7;
          color: #99a3a7;

          &:hover {
            color: #ff4949;
            border-color: #ff4949;
          }
        }

        .follow-btn {
          background-color: #0096ff;
          border: 1px solid #0096ff;
          color: #ffffff;

          &:hover {
            background-color: #007ad9;
          }
        }
      }
    }
  }

  .loading-more,
  .no-more {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 16px;
    color: #99a3a7;
    font-size: 0.9rem;
  }

  .no-more {
    color: #6c7a83;
    margin-top: 8px;
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
